from flask_jwt_extended import get_current_user
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from app.serve.user.auth import admin_required, tokens, login_required
from app.util.exception import WtreesReturn, ErrorType
from app.serve.user.user import UserServe
from app.serve.user.groups import GroupServe
from app.serve.user.permission import PermissionServer
from app.util.common import split_group


class UserLoginApi(Resource):
    post_data = RequestParser()
    post_data.add_argument("username", type=str, help='用户名', required=True)
    post_data.add_argument("password", type=str, help='密码', required=True)

    def post(self):
        args = self.post_data.parse_args()
        user = UserServe.verify(username=args['username'], password= args['password'])
        # try:
        #     user = UserServe.verify(args['username'], args['password'])
        # except Exception as error:
        #     return WtreesReturn.error(error)

        access_token, refresh_token = tokens(user, True)
        data = {"access_token": access_token, "refresh_token": refresh_token}
        return WtreesReturn.data(ErrorType.OK, data=data)


class UserRegister(Resource):
    post_data = RequestParser()
    post_data.add_argument("id", type=str, help='用户ID', required=False)
    post_data.add_argument("username", type=str, help='用户名', required=True)
    post_data.add_argument("password", type=str, help='密码', required=False)
    post_data.add_argument("nickname", type=str, help='用户昵称', required=True)
    post_data.add_argument("avatar", type=str, help='用户头像', required=False)
    post_data.add_argument("email", type=str, help='邮箱', required=False)
    post_data.add_argument("group_id", type=str, help='角色ID', required=False)

    @login_required
    def post(self):
        args = self.post_data.parse_args()
        if args['id']:
            UserServe.user_alter(args)

        else:
            UserServe.user_creation(args)
        return WtreesReturn.data(ErrorType.OK)


class ResUserApi(Resource):

    @login_required
    def get(self):
        user = get_current_user()
        groups = GroupServe.group_user(user.id)
        group_ids = [group.id for group in groups]
        _permissions = PermissionServer.role_group_ids(group_ids)
        permission_list = [{"permission": permission.name, "module": permission.module} for permission in _permissions]
        res = split_group(permission_list, "module")
        setattr(user, "permissions", res)

        return WtreesReturn.data(ErrorType.OK, data=user)


class UserListApi(Resource):
    get_data = RequestParser()
    get_data.add_argument("name", type=str, help='用户名', required=False)

    @login_required
    def get(self):
        data = UserServe.user_all()
        return WtreesReturn.data(ErrorType.OK, data=data.items, page=data.page_info())
